//
//  HMPictureView.swift
//  SinaWeibo
//
//  Created by apple on 16/9/26.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

private let cellID = "HMPictureViewCellId"

class HMPictureView: UICollectionView {
    
    var pictureInfos: [HMStatusPictureInfo]? {
        didSet {
            testLabel.text = "\(pictureInfos?.count ?? 0)张"
            print(testLabel.frame)
            //刷新视图 数据一旦发生了修改之后就应该reloadData 配图视图会复用
            reloadData()
        }
    }

    override func awakeFromNib() {
        
        //显示数据 设置数据源对象
        self.dataSource = self
        self.backgroundColor = randomColor()
        
        self.addSubview(testLabel)
        
        testLabel.snp.makeConstraints { (make) in
            make.center.equalTo(self)
        }
        
        //注册cell
        self.register(HMPictureCell.self, forCellWithReuseIdentifier: cellID)
        //获取layout对象
        //let layout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
    }

    //测试label
    private lazy var testLabel: UILabel  = {
        let l = UILabel(title: "", textColor: UIColor.black, fontSize: 30)
        
        return l
    }()

}


//配图视图的数据源方法
extension HMPictureView: UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return pictureInfos?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellID, for: indexPath) as! HMPictureCell
        //设置数据
        cell.pictureInfo = pictureInfos![indexPath.item]
        return cell
    }
    
}



//一个文件中可以写多个类
class HMPictureCell: UICollectionViewCell {
    
    var pictureInfo: HMStatusPictureInfo? {
        didSet {
            let url = URL(string: pictureInfo?.thumbnail_pic ?? "")
            imageView.sd_setImage(with: url)
        }
    }
    
    //添加一个 iv
    override init(frame: CGRect) {
        super.init(frame: frame)
        //添加子视图
        self.contentView.addSubview(imageView)
        //设置约束
        imageView.snp.makeConstraints { (make) in
            make.edges.equalTo(self.contentView.snp.edges)
        }
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    private lazy var imageView: UIImageView = {
        let iv = UIImageView()
        //设置图片显示样式

        //iv.contentMode = .scaleToFill   图片比例失真
        //iv.contentMode = .scaleAspectFit 造成图片视图显示不满
        iv.contentMode = .scaleAspectFill
        //手写代码设置的时候需要手动设置裁剪 xib/sb 自动设置裁剪
        iv.clipsToBounds = true
        return iv
    }()
}
